<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Cache;
class Category extends Model
{

    protected $table = 'categories';
    protected $guarded = [];
    
    public function children()
    {
        return $this->hasMany('App\Model\Category', 'parent_id', 'id');
    }

    public function children_api()
    {
        return $this->hasMany('App\Model\Category', 'parent_id', 'id')->where('is_show',1);
    }

    //一个分类对应多个服务
    public function hotelreferral()
    {
        return $this->hasMany('App\Model\HotelReferral');
    }

    /**
     * 清除缓存
     */
    static function clear()
    {
        Cache::forget('xHotel_category_categories');
    }

    /**
     * 生成分类数据
     * @return mixed
     */
    static function get_categories()
    {
        $categories = Cache::rememberForever('xHotel_category_categories', function () {
            return self::with(['children' => function ($query) {
                $query->orderBy('sort_order');
            }])->where('parent_id', 0)->orderBy('sort_order')->get();
        });

        return $categories;
    }

    /**
     * 检查是否有子栏目
     */
    static function check_children($id)
    {
        $category = self::with('children')->find($id);
        if ($category->children->isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 检查是否有图文
     */
    static function is_hotel($id)
    {
        $category = self::with('hotelreferral')->find($id);
        if ($category->hotelreferral->isEmpty()) {
            return true;
        }
        return false;
    }
}
